package com.yzw.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yzw.dto.DataGridResult;
import com.yzw.dto.QueryDTO;
import com.yzw.dto.UserDTO;
import com.yzw.pojo.SysUser;
import com.yzw.service.SysUserService;
import com.yzw.utils.MD5Utils;
import com.yzw.utils.R;
import com.yzw.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@Api("用户管理相关接口")
@RestController
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DefaultKaptcha kaptcha;

    @ApiOperation("验证码")
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response){
        // 缓存设置-设置不缓存（可选操作）
        response.setHeader("Cache-Control","no-store, no-cache");
        // 设置响应内容
        response.setContentType("image/jpg");
        //生成验证码
        String text = kaptcha.createText();//文本
        //生成图片
        BufferedImage image = kaptcha.createImage(text);
        //验证码存储到shiro的 session
        ShiroUtils.setKaptcha(text);
        try {
            //返回到页面
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @ApiOperation("登录接口")
    @RequestMapping("/sys/login")
    @ResponseBody
    public R login(@RequestBody UserDTO userDTO){
        try {
            //比对验证码
            String serverKaptcha = ShiroUtils.getKaptcha();
            if(!serverKaptcha.equalsIgnoreCase(userDTO.getCaptcha())){
                return R.error("验证码错误");
            }
            Subject subject = SecurityUtils.getSubject();
//            String newPass = MD5Utils.md5(userDTO.getPassword(),userDTO.getUsername(),1024);
            UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUsername(),userDTO.getPassword());
//            UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUsername(),newPass);
            if(userDTO.isRememberMe()){
                token.setRememberMe(true);
            }
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error("账号不存在");
        }catch (LockedAccountException e){
            return R.error("账号被冻结");
        }catch (IncorrectCredentialsException e){
            return R.error("密码错误");
        }

        //会去调用自定义的realm
        return R.ok();
    }
    @ApiOperation("分页查询用户接口")
    @RequestMapping("/sys/user/list")
    @ResponseBody
    public DataGridResult findUser(QueryDTO queryDTO){
        return sysUserService.findUserByPage(queryDTO);
    }
    @ApiOperation("导出用户Excel表格")
    @RequestMapping("/sys/user/export")
    public void exportUser(HttpServletResponse response){
        Workbook workbook = sysUserService.exportUser();
        try {
            //设置响应头
            response.setContentType("application/octet-stream");//所有文件都支持
            String fileName = "员工信息.xls";
            fileName = URLEncoder.encode(fileName,"utf-8");
            response.setHeader("content-disposition","attachment;filename="+fileName);
            //文件下载
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation("退出")
    @RequestMapping("/logout")
    public String logout(){
        ShiroUtils.logout();
        return "login";
    }
    @ApiOperation("获得shiro中当前用户信息")
    @RequestMapping("/sys/user/info")
    @ResponseBody
    public R userinfo(){
        //可以从shiro中获取
            SysUser userEntity = ShiroUtils.getUserEntity();
        return R.ok().put("user",userEntity);
    }

    /**
     * 新增
     * @param sysUser
     * @return
     */
    @ApiOperation("新增用户")
    @RequestMapping("/sys/user/save")
    @ResponseBody
    public R saveUser(@RequestBody SysUser sysUser){
        return sysUserService.saveUser(sysUser);
    }

    /**
     * 用户删除
     * @param ids
     * @return
     */
    @ApiOperation("删除")
    @RequestMapping("/sys/user/del")
    @ResponseBody
    public R deleteMenu(@RequestBody List<Long> ids){
        return  sysUserService.deleteMenu(ids);
    }
    @ApiOperation("根据id查询用户")
    @GetMapping("/sys/user/info/{userId}")
    public R findUserById(@PathVariable("userId") long userId){
        return  sysUserService.selectByUserId(userId);
    }
    @ApiOperation("更新用户")
    @RequestMapping("/sys/user/update")
    public R update(@RequestBody SysUser sysUser){
        try {
            int i = sysUserService.update(sysUser);

            return  R.ok();

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("修改失败");
        }

    }

    /**
     * 修改密码
     * @param password
     * @param newPassword
     * @return
     */
    @RequestMapping("/sys/user/password")
    public R password(String password,String newPassword){
        try {

            return  sysUserService.password(password, newPassword);

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("修改失败");
        }

    }



}
